<?php

namespace app\middleware;

use think\Request;

class CheckAdminUserRolePermission
{
    public function handle(Request $request, \Closure $next)
    {
        $adminUserInfo = cache('admin_user_info');
        $adminRole = \app\controller\AdminUsersRole::getUsersRole(new \app\model\AdminUsersRole(), $adminUserInfo['id']);
        $adminRoleMenu = \app\controller\AdminRoleMenu::getSignInUserMenuPermisson(new \app\model\AdminRoleMenu(), $adminRole[0]['role_id']);
        foreach ($adminRoleMenu as $k => $v)
        {
            $adminMenuData[] = $adminRoleMenu[$k]['menu_list'];
        }
        foreach ($adminMenuData as $menuValue)
        {
            foreach ($menuValue as $childValue)
            {
                $adminInitMenuData[] = $childValue;
            }
        }
        $nowUserMenuData = array_unique($adminInitMenuData, SORT_REGULAR);
        foreach ($nowUserMenuData as $nowUserMenuValue)
        {
            foreach ($nowUserMenuValue['child'] as $userMenuValue)
            {
                $initUserMenuList[] = $userMenuValue['menu_url'];
            }
        }
        $url = $request->url();
        $initUrl = substr($url, 0, strpos($url,'?'));
        return in_array($url, $initUserMenuList) == true ?
            $next($request) : $this->checkUrlAgain($initUrl, $initUserMenuList, $next($request));
    }

    private function checkUrlAgain(string $initUrl, array $initUserMenuList, $next)
    {
        return in_array($initUrl, $initUserMenuList) == true ?
            $next : redirect('/404');
    }
}
